<!--
 * @Author: Guiter 1336263157@qq.com
 * @Date: 2023-11-18 17:47:56
 * @LastEditors: Guiter 1336263157@qq.com
 * @LastEditTime: 2023-11-29 10:34:59
 * @FilePath: \nuxt3-music-player\src\components\Login\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script lang="ts" setup>
import { getKey, createKey, checkKey } from '../../server/api/login';
import check from './check.vue';

/**
 * changeLoginShow：展示或者隐藏登录窗口
 */
const _emit = defineEmits<(event: 'changeLoginShow') => void>();

/**
 * 用户仓库
 */
const userStore = useUserStore();

/**
 * 二维码图片地址
 */
const qrimgUrl = ref<string>('/login/bg.jpg');

/**
 * 获取二维码
 */
const getCode = async (): Promise<void> => {
  /* 获取密钥 */
  const res = await getKey();
  if (res !== undefined && res !== null) {
    /* 获取二维码图片地址 */
    const result = await createKey(res.unikey);
    console.log(result);
    qrimgUrl.value = result.qrimg;
    if (qrimgUrl.value !== undefined) {
      checkCode(res.unikey);
    }
  }
};

/**
 * 时间
 */
let timer: NodeJS.Timeout;

/**
 * 确认登录或者登录过期判断
 */
const confirm = ref<number>(801);

/**
 * 检查二维码
 */
const checkCode = (key: string): void => {
  timer = setInterval(async (): Promise<void> => {
    const res = await checkKey(key);
    confirm.value = res.code;
    if (res.code === 803) {
      close();
      userStore.setToken(res.cookie);
      clearInterval(timer);
      /* 获取用户的所有信息 个人资料 歌单信息 歌单数量等 */
      await getAllInfo();
      useMessage({
        message: '登录成功',
        type: 'success'
      });
    }
    if (res.code === 800) {
      // '过期'
      confirm.value = 800;
      clearInterval(timer);
    }
  }, 2000);
};

/**
 * 展示窗口
 */
const loginShow = ref<boolean>(false);

/**
 * 关闭登录窗口
 */
const close = (): void => {
  loginShow.value = false;
  setTimeout(() => {
    _emit('changeLoginShow');
  }, 400);
};

onMounted(async () => {
  loginShow.value = true;
  await getCode();
});

onUnmounted(() => {
  clearInterval(timer);
});
</script>

<template>
  <div class="absolute left-0 top-0 z-10 select-none bg-gray-500/50 shadow-2xl">
    <Transition name="box">
      <!-- 盒子 -->
      <div
        v-show="loginShow"
        class="trans position-default border-default h-114 w-93 flex flex-col bg-white"
      >
        <!-- 关闭 -->
        <div class="box-border p-1">
          <svg-icon class="float-right h-7 w-7 cursor-pointer" name="close" @click="close" />
        </div>
        <div class="h-full">
          <check :code="confirm" :qrimg-url="qrimgUrl" class="flex-1"></check>
        </div>
      </div>
    </Transition>
  </div>
</template>

<style scoped>
.box-enter-active,
.box-leave-active {
  transition: all 0.5s ease;
}

.box-enter-from,
.box-leave-to {
  transform: translate(-50%, -58%);
  opacity: 0;
}
</style>
